﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Star.Tools.Attributes
{
    /// <summary>
    /// 特性扩展类
    /// </summary>
    public static class AttributeHelper<T> where T : class
    {
        private static readonly ConcurrentDictionary<Type, T> AttributeDic =
            new ConcurrentDictionary<Type, T>();

        /// <summary>
        /// 获取实体特性信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        /// <returns></returns>
        public static T GetAttribute(Type type)
        {
            return AttributeDic.GetOrAdd(type, item =>
            {
                var customAttribute = type.GetCustomAttribute(typeof(T));

                if (customAttribute!=null)
                    return customAttribute as T;

                return null;
            });

        }

        private static Dictionary<string, string> GetDescription()
        {
            Type type = typeof(T);
            PropertyInfo[] pArray = type.GetProperties(); 

            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            foreach (PropertyInfo p in pArray)
            {
                var description = GetDescriptionName(p.Name);
                if (string.IsNullOrEmpty(description)) continue;
                keyValues.Add(p.Name, description);
            }

            return keyValues;
        }
        /// <summary>
        /// 获取Description的值
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        private static string GetDescriptionName(string field)
        {
            if (string.IsNullOrEmpty(field)) return "";
            AttributeCollection attributes = TypeDescriptor.GetProperties(typeof(T))[field].Attributes;
            DescriptionAttribute myAttribute = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
            if (myAttribute == null) return "";
            return myAttribute.Description;
        }

    }
}
